package data.join.com.media;

import android.content.Context;
import android.text.TextUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.zip.ZipOutputStream;

import data.join.com.database.bean.CommandBean;
import data.join.com.network.RetrofitManager;
import data.join.com.network.gson.UpdateCommandRequest;
import data.join.com.socket.MqttCommand;
import data.join.com.utils.BaseThread;
import data.join.com.utils.FileUtils;
import data.join.com.utils.LogcatHelper;
import data.join.com.utils.MyLog;
import data.join.com.utils.QiniuApi;
import data.join.com.utils.QuickShPref;
import data.join.com.utils.WakeLockUtils;
import data.join.com.utils.ZipUtils;
import retrofit2.Call;

/**
 * Created by Administrator on 2017/11/8.
 */

public class UploadLogThread extends BaseThread {

    private static String TAG = UploadLogThread.class.getSimpleName();

    private static UploadLogThread mInstance;

    private Context mContext;

    private UploadLogThread(Context context){
        this.mContext = context;
    }

    private String commandId;

    public static UploadLogThread getInstance(Context context){
        if(mInstance == null){
            mInstance = new UploadLogThread(context);
        }
        return mInstance;
    }

    public UploadLogThread(Context context,String commandId){
        this.mContext = context;
        this.commandId = commandId;
    }

    @Override
    public void run() {
        synchronized (UploadLogThread.class) {
            WakeLockUtils.getDefault(mContext).acquireWakeLock(TAG);
            startUploadLog();
            WakeLockUtils.getDefault(mContext).releaseWakeLock(TAG);
        }
    }

    private void startUploadLog(){

        String zipFile = generateLogZipFile();

        if(!TextUtils.isEmpty(zipFile)){
           QiniuApi.UploadResult uploadResult = QiniuApi.getDefault().startUploadAsync(zipFile,QiniuApi.getQiniuLogToken(zipFile));
           if(uploadResult != null){
               MyLog.D(TAG,"startUploadLog success,key="+uploadResult.cloudKey);
               if(sendCommandResult(commandId,uploadResult.cloudKey)){
                   MyLog.D(TAG,"sendCommandResult success");
               }else {
                   if (sendCommandResult(commandId, uploadResult.cloudKey)) {
                       MyLog.D(TAG, "sendCommandResult again  success");
                   } else {
                       MyLog.D(TAG, "sendCommandResult fail after twice");
                   }
               }
           }else{
               MyLog.D(TAG,"startUploadLog fail to upload qiniu");
           }
        }else{
            MyLog.D(TAG,"startUploadLog fail zipFile is NULL");
        }

        FileUtils.deleteFile(zipFile);
    }

    private String generateLogZipFile(){
        List<File> logList = getLogFileList();
        String logZipName = getLogZipName();

        try {
            ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(logZipName), ZipUtils.BUFF_SIZE));

            for (File log:logList){
                ZipUtils.zipFile(log, zipOut, "");
            }

            zipOut.close();
        } catch (Exception e) {
            e.printStackTrace();
            logZipName = null;
        }
        return logZipName;
    }

    private List<File> getLogFileList(){
        List<File> list = new ArrayList<>();

        File dir = new File(LogcatHelper.PATH_LOGCAT);

        File[] files = dir.listFiles();

        for(File file:files){
            if(LogcatHelper.isLogFile(file.getName())){
                list.add(file);
            }
        }

        return list;
    }

    private String getLogZipName(){
        String imei = QuickShPref.getInstance().getString(QuickShPref.DeviceImei);

        String name = LogcatHelper.PATH_LOGCAT + File.separator + "joinLogZip-"+imei+"-"+System.currentTimeMillis()+".zip";

        return name;
    }

    private boolean sendCommandResult(String commandId, String logKey){
        boolean ret = false;

        UpdateCommandRequest commandRequest = new UpdateCommandRequest();
        HashMap<String,String> content = new HashMap<>();

        content.put("key",logKey);
        content.put("command_type", MqttCommand.TYPE_UPLOAD_LOG);

        commandRequest.content = content;

        Call<Object> objectCall = RetrofitManager.getApiService().updateCommand(commandId,RetrofitManager.getBodyByJson(commandRequest));

        try {
            ret = objectCall.execute().isSuccessful();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }
}
